package com.alatus.manager;

import com.alatus.mapper.TClueMapper;
import com.alatus.mapper.TCustomerMapper;
import com.alatus.model.TClue;
import com.alatus.model.TCustomer;
import com.alatus.query.CustomerQuery;
import com.alatus.util.JWTUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
public class CustomerManager {
    @Resource
    private TCustomerMapper tCustomerMapper;
    @Resource
    private TClueMapper tClueMapper;

    @Transactional(rollbackFor = Exception.class)
    public Boolean transferCustomer(CustomerQuery customerQuery) {
        TClue tClue = tClueMapper.selectByPrimaryKey(customerQuery.getClueId());
        if(tClue.getState() == -1){
            throw new RuntimeException("该线索已被使用");
        }
        else{
            TCustomer tCustomer = new TCustomer();
            BeanUtils.copyProperties(customerQuery,tCustomer);
            tCustomer.setCreateTime(new Date());
            tCustomer.setCreateBy(JWTUtils.parseUserFromJWT(customerQuery.getToken()).getId());
            tCustomerMapper.insert(tCustomer);
            TClue clue = new TClue();
            clue.setId(customerQuery.getClueId());
            clue.setState(-1);
            tClueMapper.updateByPrimaryKeySelective(clue);
            return true;
        }
    }
}
